import * as React from 'react';
import classNames from 'classnames';
import { useState } from 'react'
import Star from './Star';

export interface RateProps {
	children?: React.ReactNode;
	className?: string;
	character?: React.ReactNode;
	count?: number;
	value?: number;
	disabled?: boolean;
	allowClear?: boolean;
	defaultValue?: number;
	tooltips?: Array<string>;

	onBlur?: () => void;
	onChange?: (index:number) => void;
	onFocus?: () => void;
	onHoverChange?: (index:number) => void;
	onKeyDown?: (e: React.MouseEvent<HTMLElement>) => void;

}

const Rate: React.FC<RateProps> = props => {
	const prefixCls = 'bh-rate';
	const {
		children,
		className,
		character = '★',
		count = 5,
		value = 2,
		disabled = false,
		allowClear = true,
		defaultValue = 0,
		tooltips = [],

		onBlur,
		onChange,
		onFocus,
		onHoverChange,
		onKeyDown,

		...restProps
	} = props;

	const classString1 = classNames(
		prefixCls,
		className,
		{
			[`${prefixCls}-disabled`]: disabled,
		},
	);
	const [hoverValue, setHoverValue] = useState(-1);
	const [newValue, setNewValue] = useState(value);

	//鼠标-移出
	const onMouseLeaveCallback = () => {
		setHoverValue(-1);
		onBlur && onBlur();
	}
	const onKeyDownCallback = (event:any) => {
		onKeyDown && onKeyDown(event);
	};
	//鼠标-移入
	const onHover = (index:number) => {
		if(disabled) {
			return;
		}
		setHoverValue(index);
		onHoverChange && onHoverChange(index);
		onFocus && onFocus();
	}
	//鼠标-点击
	const onClick = (index:number) => {
		if(disabled) {
			return;
		}
		let indexNew = index;
		if(allowClear && index == newValue) {
			setHoverValue(-1);
			indexNew = -1;
		}else {
			indexNew = index;
		}

		setNewValue(indexNew);

		onChange && onChange(indexNew);
	}
	
	let stars = [];
	for(let index = 0; index < count; index++) {
		stars.push(index)
	}

	return (
		<ul {...restProps} className={classString1} onMouseLeave={onMouseLeaveCallback} onClick={onKeyDownCallback}>
		    {stars.map((item, index) => {
		    	return <Star 
		    	    index={index} 
		    	    character={character}
		    	    disabled={disabled}
		    	    count={count}
		    	    value={hoverValue === -1 ? newValue : hoverValue}
		    	    onClick={onClick}
		    	    onHover={onHover}
		    	    tooltip={tooltips[index]}
		    	    key={index}></Star>;
		    })}
		</ul>
	)
};

export default Rate;